package com.ruoyi.ams.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.ams.domain.AmsAssetScrap;
import com.ruoyi.ams.domain.AmsAssetScrapDetail;
import com.ruoyi.ams.service.AmsReusingService;
import com.ruoyi.ams.service.IAmsAssetScrapDetailService;
import com.ruoyi.ams.service.IAmsAssetScrapService;
import com.ruoyi.common.core.domain.KeyValueVo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.system.controller.SysDeptController;
import com.ruoyi.system.controller.SysUserController;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 清理报废Controller
 * 
 * @author yfkj
 * @date 2022-05-16
 */
@RestController
@RequestMapping("/ams/scrap")
public class AmsAssetScrapController extends BaseController
{
    @Autowired
    private IAmsAssetScrapService amsAssetScrapService;
    @Autowired
    private AmsReusingService amsReusingService;
    @Autowired
    private IAmsAssetScrapDetailService assetScrapDetailService;
//    @Autowired
//    private RemoteUserService remoteUserService;
//    @Autowired
//    private RemoteDeptService remoteDeptService;
    @Autowired
    private SysUserController userController;
    @Autowired
    private SysDeptController deptController;

    /**
     * 查询清理报废列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:scrap:list")
    @ApiOperation(value = "获取清理报废列表")
    @GetMapping("/getAmsAssetScrapList")
    public TableDataInfo getAmsAssetScrapList(AmsAssetScrap amsAssetScrap)
    {
        QueryWrapper<AmsAssetScrap> wrapper = new QueryWrapper<>();
        if (amsAssetScrap.getStatus() != null) {
            wrapper.eq(AmsAssetScrap.STATUS, amsAssetScrap.getStatus());
        }
        wrapper.orderByDesc(AmsAssetScrap.SCRAP_ID);
        startPage();
        List<AmsAssetScrap> list = amsAssetScrapService.list(wrapper);

        CompletableFuture<R<Map<Long, SysUser>>> future1 = CompletableFuture.supplyAsync(() ->
               userController.getAllUsers());

        CompletableFuture<R<Map<Long, SysDept>>> future2 = CompletableFuture.supplyAsync(() ->
                deptController.getAllDeptsMap());

        R<Map<Long, SysUser>> allUsers = new R<>();
        R<Map<Long, SysDept>> allDeptsMap = new R<>();
        try {
            allUsers = future1.get();
            if (allUsers.getCode() == R.FAIL) {
                return amsReusingService.resovleError();
            }
            allDeptsMap = future2.get();
            if (allDeptsMap.getCode() == R.FAIL) {
                return amsReusingService.resovleError();
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        Map<Long, SysUser> userMap = allUsers.getData();
        Map<Long, SysDept> deptMap = allDeptsMap.getData();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy.MM.dd");

        List<AmsAssetScrapDetail> scrapDetails = assetScrapDetailService.list();

        HashMap<Long, String> assetIdTypeNameMap = amsReusingService.getAssetIdTypeNameMap();

        for (AmsAssetScrap scrap : list) {
            if (scrap.getScrapTime() != null) {
                scrap.setScrapTimeStr(fmt.format(new Date(scrap.getScrapTime())));
            }
            if (scrap.getScrapUserId() != null) {
                SysUser sysUser = userMap.get(scrap.getScrapUserId());
                if (sysUser != null) {
                    scrap.setScrapUserName(sysUser.getNickName());
                }
            }
            if (scrap.getBusinessDeptId() != null) {
                SysDept sysDept = deptMap.get(scrap.getBusinessDeptId());
                if (sysDept != null) {
                    scrap.setBusinessDeptName(sysDept.getDeptFullName());
                }
            }
            List<String> assetTypeNames = new ArrayList<>();
            for (AmsAssetScrapDetail scrapDetail : scrapDetails) {
                if (scrapDetail.getScrapId().equals(scrap.getScrapId())) {
                    String assetTypeName = assetIdTypeNameMap.get(scrapDetail.getAssetId());
                    if (assetTypeName != null) {
                        assetTypeNames.add(assetTypeName);
                    }
                }
            }
            scrap.setAssetNames(assetTypeNames);
        }
        return getDataTable(list, 10);
    }


    /**
     * 获取清理报废详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:scrap:query")
    //@ApiOperation(value = "获取清理报废详情")
    @GetMapping(value = "/getAmsAssetScrapById")
    public AjaxResult getAmsAssetScrapById(@RequestParam("scrapId") Long scrapId)
    {
        return AjaxResult.success(amsAssetScrapService.selectAmsAssetScrapByScrapId(scrapId));
    }

    /**
     * 新增清理报废
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:scrap:add")
    @Log(title = "清理报废", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增清理报废")
    @PostMapping(value = "/addAmsAssetScrap")
    public AjaxResult addAmsAssetScrap(@RequestBody AmsAssetScrap amsAssetScrap)
    {
        //保存资产报废基本信息
        amsAssetScrap.setScrapSn(amsReusingService.createSn());
        amsAssetScrap.setScrapTime(System.currentTimeMillis());
        amsAssetScrapService.save(amsAssetScrap);

        //保存资产报废详情信息
        if (amsAssetScrap.getAssetIds().length == 0) {
            return AjaxResult.error("请至少选择一个资产");
        }
        List<AmsAssetScrapDetail> scrapDetails = new ArrayList<>();
        for (Long assetId : amsAssetScrap.getAssetIds()) {
            AmsAssetScrapDetail scrapDetail = new AmsAssetScrapDetail();
            scrapDetail.setAssetId(assetId);
            scrapDetail.setScrapId(amsAssetScrap.getScrapId());
            scrapDetails.add(scrapDetail);
        }
        assetScrapDetailService.saveBatch(scrapDetails);
        return AjaxResult.success();
    }

    /**
     * 修改清理报废
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:scrap:edit")
    @Log(title = "清理报废", businessType = BusinessType.UPDATE)
    //@ApiOperation(value = "修改清理报废")
    @PostMapping(value = "/editAmsAssetScrap")
    public AjaxResult editAmsAssetScrap(@RequestBody AmsAssetScrap amsAssetScrap)
    {
        //修改资产报废基础信息
        amsAssetScrapService.updateById(amsAssetScrap);
        //修改资产报废详情信息
        if (amsAssetScrap.getAssetIds().length > 0) {
            //先删除之前的资产报废详情信息
            assetScrapDetailService.remove(new QueryWrapper<AmsAssetScrapDetail>()
                    .eq(AmsAssetScrapDetail.SCRAP_ID, amsAssetScrap.getScrapId()));
            //然后保存现有的资产报废详情信息
            List<AmsAssetScrapDetail> scrapDetails = new ArrayList<>();
            for (Long assetId : amsAssetScrap.getAssetIds()) {
                AmsAssetScrapDetail scrapDetail = new AmsAssetScrapDetail();
                scrapDetail.setAssetId(assetId);
                scrapDetail.setScrapId(amsAssetScrap.getScrapId());
                scrapDetails.add(scrapDetail);
            }
            assetScrapDetailService.saveBatch(scrapDetails);
        }
        return toAjax(amsAssetScrapService.updateAmsAssetScrap(amsAssetScrap));
    }

    /**
     * 删除清理报废
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:scrap:remove")
    @Log(title = "清理报废", businessType = BusinessType.DELETE)
	@GetMapping("/removeAmsAssetScraps")
    public AjaxResult removeAmsAssetScraps(@RequestParam Long[] scrapIds)
    {
        return toAjax(amsAssetScrapService.deleteAmsAssetScrapByScrapIds(scrapIds));
    }
    @GetMapping("/getAmsAssetScrapNamesForSelect")
    //@ApiOperation(value = "获取清理报废名称列表用于下拉搜索")
    public AjaxResult getAmsAssetScrapNamesForSelect()
    {
        List<AmsAssetScrap> list = amsAssetScrapService.list();//自行加条件
        List<KeyValueVo> resultList = new ArrayList<>();
        for (AmsAssetScrap amsAssetScrap: list ) {
            KeyValueVo vo = new KeyValueVo();
            //vo.setKey(it.getId());
            //vo.setValue(it.getName());
            resultList.add(vo);
        }
        return AjaxResult.success(resultList);
    }
    /**
     * 导出清理报废列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:scrap:export")
    @Log(title = "清理报废", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAmsAssetScrap")
    public String exportAmsAssetScrap(HttpServletResponse response, AmsAssetScrap amsAssetScrap) throws IOException
    {
        List<AmsAssetScrap> list = amsAssetScrapService.selectAmsAssetScrapList(amsAssetScrap);
        ExcelUtil<AmsAssetScrap> util = new ExcelUtil<AmsAssetScrap>(AmsAssetScrap.class);
        util.exportExcel(response, list, "清理报废数据");
        return "";
    }

}
